package pow

import (
	"bytes"
	"day0304/tools"
	"day0304/transaction"
	"math/big"
	"strconv"
)

const BITS = 15

//type ProofofWork struct {
//	//Block  *block.Block //给哪个区块工作
//	PrevHash []byte
//	TimeStamp int64
//	Data []byte
//	Target *big.Int
//}
type ProofOfWork struct {
	//PrevHash  []byte
	//TimeStamp int64
	//Data      []byte
	Block BlockInterface
	Target    *big.Int
}
type BlockInterface interface {
	GetPrevHash() []byte
	GetTimeStamp() int64
	GetData() []transaction.Transaction
}


//func NewPow(data []byte,timeStamp int64,prevHash []byte)*ProofOfWork{
//
//	//创建大整数类型变量
//	target:=big.NewInt(1) //1
//	target = target.Lsh(target,255-BITS)
//	pow:=ProofOfWork{
//		PrevHash:  prevHash,
//		TimeStamp: timeStamp,
//		Data:data,
//		Target: target,
//	}
//	return &pow
//}
func NewPow(block BlockInterface)*ProofOfWork{

	//创建大整数类型变量
	target:=big.NewInt(1) //1
	target = target.Lsh(target,255-BITS)
	pow:=ProofOfWork{
		Block: block,
		Target: target,
	}
	return &pow
}

//计算随机数
func (pow *ProofOfWork)Run()([]byte,int64){
	var nonce int64
	nonce = 0
	block := pow.Block
	timeByte:=[]byte(strconv.FormatInt(block.GetTimeStamp(),10))




	//转换 把[]byte 转成 大整数类型
	num:=big.NewInt(0)

	txsBytes :=[]byte{}
	for{
		nonceByte:=[]byte(strconv.FormatInt(nonce,10))
		for _,value:=range block.GetData(){
			txBytes, _ := value.Serialize()
			txsBytes = append(txsBytes,txBytes...)
		}

		hashByte:=bytes.Join([][]byte{block.GetPrevHash(),txsBytes,timeByte,nonceByte},[]byte{})
		hash:=tools.SetHash(hashByte)
		//fmt.Println("正在寻找nonce,当前的nonce为",nonce)
		num=num.SetBytes(hash)
		if(num.Cmp(pow.Target)==-1 ){
			return hash,nonce
		}
		nonce++
	}
	//	hashByte:=bytes.Join([][]byte{pow.PrevHash,pow.Data,timeByte,nonceByte},[]byte{})
	//	hash:=tools.SetHash(hashByte)
	//	//fmt.Println("正在寻找nonce,当前的nonce为",nonce)
	//	num=num.SetBytes(hash)
	//	if(num.Cmp(pow.Target)==-1 ){
	//		return hash,nonce
	//	}
	//	nonce++
	//}
	/*
		if(a < target){
		}
	*/

	//pow.Target
	return nil, 0
}